package cn.edu.controller;

import cn.edu.entity.User;
import cn.edu.service.IUserService;
import cn.edu.utils.JWTUtils;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @PackageName: cn.edu.controller
 * @ClassName: UserController
 * @Description:
 * @author: RZS
 * @date: 2021/7/14  22:27
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 用户登录接口
     * @param user
     * @return
     */
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody User user){
        log.info("用户名: [{}]", user.getUsername());
        log.info("密码: [{}]", user.getPassword());

        Map<String, Object> map = new HashMap<>();
        //try {
            // 获取用户登录数据
            User userDB = userService.login(user);
            // 判断用户密码是否正确
            if (userDB.getPassword().equals(user.getPassword())){
                // 密码正确

                // 创建map集合，用于存放载体数据 payload
                Map<String, String> payload = new HashMap<>();
                payload.put("id", userDB.getId());
                payload.put("name", userDB.getUsername());
                // 生成令牌
                String token = JWTUtils.getToken(payload);
                // 封装响应数据
                map.put("state", true);
                map.put("msg", "登录认证成功");
                // 封装token
                map.put("token", token);
            }else {
                throw new RuntimeException("登录认证失败，用户名或密码错误");
            }
        /*} catch(Exception e) {
            // 封装响应数据
            map.put("state", false);
            map.put("msg", "登录认证失败，用户名或密码错误");
        }*/
        return map;
    }


    /**
     * 验证token
     * @param request
     * @return
     */
    @PostMapping("/test")
    public Map<String, Object> test(HttpServletRequest request){
        // 从请求头中获取token信息
        String token = request.getHeader("token");
        Map<String, Object> map = new HashMap<>();
        log.info("当前token为: [{}]", token);
        // 判断是否有tokenxx
        if(token != null && !StringUtils.isEmpty(token)){
            try {
                // 验证令牌
                JWTUtils.verify(token);
                map.put("state", true);
                map.put("msg", "请求成功!");
                return map;
            } catch (SignatureVerificationException e) {
                e.printStackTrace();
                map.put("msg", "无效签名");
            } catch (TokenExpiredException e) {
                e.printStackTrace();
                map.put("msg", "token过期!");
            } catch (AlgorithmMismatchException e) {
                e.printStackTrace();
                map.put("msg", "token算法不一致!");
            } catch (Exception e) {
                e.printStackTrace();
                map.put("msg", "token无效!!");
            }
            map.put("state", false);
            return map;
        }
        map.put("state", false);
        return map;
    }
}
